//
//  OrderDetailViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/9/10.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "OrderDetailViewController.h"

#import "MeatOrderLocationCell.h"
#import "OrderDetailCommonCell.h"
#import "OrderHeaderCell.h"
#import "OrderBodyCell.h"
#import "OrderNomalCell.h"
#import "OrderDetailFooterCell.h"
#import "OrderDetailFooterView.h"
#import "LogisticsViewController.h"

#import "OrderCancelBox.h"
#import "MeatPayViewController.h"


@interface OrderDetailViewController ()

@property (nonatomic, strong) UIImageView *bgImg;
@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) UILabel *detailLab;
@property (nonatomic, strong) MeatOrderSumbitParam *sumbitParam;
@property (nonatomic, strong) MeatOrderDetailResultModel *model;
@property (nonatomic, strong) OrderDetailFooterView *footer;


@property (nonatomic, strong) NSArray *reasons;


@end

@implementation OrderDetailViewController

#pragma mark - view life cycle

- (void)setupUI{

    {
        self.baseNavView.navTitleLabel.text = @"订单详情";
        self.baseNavView.navTitleLabel.textColor = KWhiteColor;
        self.baseNavView.backgroundColor = KClearColor;
        self.baseNavView.line.hidden = YES;
        
        [self.baseNavView.leftNavBtn setImage:[UIImage imageNamed:@"nav_white"] forState:UIControlStateNormal];
        
        
        [self.bgImg addSubview:self.baseNavView];
    }
    
    {
        [self.view addSubview:self.bgImg];
        [self.view addSubview:self.tableView];
        [self.view addSubview:self.footer];
        [self setHeaderText];
    }
}

- (void)setHeaderText{
    
    //订单状态:1待付款3待收货4待评价6已完成
    switch ([_item.goStatus integerValue]) {
        case 1:
        {
            _titleLab.text = @"等待买家付款…";
            _detailLab.text = @"订单在23小时59分内未支付，系统将自动取消，请尽快完成支付。";
        }
            break;
            
        case 2: //代发货
        {
            _titleLab.text = @"卖家已发货…";
            _detailLab.text = @"买家已付款，等待商家发货";
        }

        case 3:
        {
            _titleLab.text = @"卖家已发货…";
            _detailLab.text = @"买家已付款，等待商家发货";
        }
            break;
        case 4:
        {
            
        }
            break;
            
        case 6:
        {
            _titleLab.text = @"交易完成";
            _detailLab.text = @"订单已完成，快来评价吧";
            
        }
            break;
            
        default:
            break;
    }
}

- (void)setupLayout
{
    [self.bgImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(177 + TJ_StatusBarHeight);
    }];

    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(62 + TJ_StatusBarHeight);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(26);
    }];

    [self.detailLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titleLab.mas_bottom).offset(5);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(17);
    }];

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.detailLab.mas_bottom).offset(5);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo( -(60 + TJ_SafeAreaBottomHeight));
    }];

    [self.footer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.tableView.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(TJ_SafeAreaBottomHeight);
    }];
    
}

- (void)initData{
    
    @weakify(self);
    MeatOrderDetailParam *param = [[MeatOrderDetailParam alloc] init];
    param.memberId = kMemberId;
    param.goStatus = self.item.goStatus;
    param.cameraSwitch = @1;
    param.goodsOrderId = self.item.goodsOrderId;
    
    [[[MeatOrderApi sharedInstance] getOrderDetailByParams:param] subscribeNext:^(MeatOrderDetailModel * _Nullable model) {
        @strongify(self);
        
        self.model = model.result;
        [self.tableView reloadData];
        
    } error:^(NSError * _Nullable error) {
        
    }];
}

//取消订单
- (void)requestCancelOrderById:(NSNumber *)goodId reason:(NSString *)reason
{
    @weakify(self);
    [[[MeatOrderApi sharedInstance] getOrderCancelByGoodId:goodId reason:reason] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        
        [self showHudWithMsg:@"取消订单成功"];
        [self refresh];
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        
        NSString *contentText = error.userInfo[NSLocalizedDescriptionKey];
        [self showHudWithMsg:contentText];
    }];
}

//确认收货
- (void)requestAcceptOrderById:(NSNumber *)goodId{
    
    @weakify(self);
    [[[MeatOrderApi sharedInstance] getOrderConfirmOverByGoodId:goodId] subscribeNext:^(NSNull * _Nullable x) {
        
        @strongify(self);
        
        [self showHudWithMsg:@"确认收货成功"];
        [self refresh];
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        
        NSString *contentText = error.userInfo[NSLocalizedDescriptionKey];
        [self showHudWithMsg:contentText];
    }];
}



#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return section == 1 ? self.model.product_json_str.count + 3 :1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0) return 90;
    if(indexPath.section == 1)
    {
        if (indexPath.row == 0) return 44;
        if (indexPath.row == 1) return 34;
        if (indexPath.row == self.model.product_json_str.count +2) return 46;
        return 76;

    }
    return 115;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionView = [[UIView alloc] init];
    sectionView.backgroundColor = KClearColor;
    return sectionView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            MeatOrderLocationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatOrderLocationCell"];
            cell.locationModel = self.model.goodOrder;
            cell.arrowBtn.hidden = YES;
    
            return cell;
            
        }
            break;
        case 1:
        {
            
            if (indexPath.row == 0) {
                
                OrderHeaderCell *headerCell = [tableView dequeueReusableCellWithIdentifier:@"OrderHeaderCell"];
                headerCell.shopName = self.item.shopName;
                headerCell.stateLab.hidden = YES;
                return headerCell;
                
            }else if (indexPath.row == 1){
                
                OrderNomalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderNomalCell"];
                cell.textLab.text = [NSString stringWithFormat:@"%@ %@", self.item.varietiesName, self.item.pigNum];
                cell.textLab.textAlignment = 0;
                return cell;
                
            }else if (indexPath.row == self.model.product_json_str.count +2){
                
                OrderDetailFooterCell *footerCell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailFooterCell"];
                footerCell.type = OrderDetailFooterCellType_OpenCamera;
                footerCell.type = OrderDetailFooterCellType_Chat;
                return footerCell;
            }
            
            OrderBodyCell *bodyCell = [tableView dequeueReusableCellWithIdentifier:@"OrderBodyCell"];
            MeatOrderDetailItemModel *detailItem = self.model.product_json_str[indexPath.row - 2];
            bodyCell.detailItem = detailItem;
            return bodyCell;

        }
            break;
            
        default:
        {
            OrderDetailCommonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailCommonCell"];
            return cell;
            
        }
            break;
    }
    
    return [UITableViewCell new];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - setter methods

#pragma mark - getter methods

- (UIImageView *)bgImg {
    if (!_bgImg) {
        _bgImg = [[UIImageView alloc] init];
        _bgImg.image = [UIImage imageNamed:@"screen_book_bg"];
        _bgImg.userInteractionEnabled = YES;
        
        [_bgImg addSubview:self.titleLab];
        [_bgImg addSubview:self.detailLab];
        
    }
    return _bgImg;
}

- (UILabel *)titleLab{
    
    if (!_titleLab) {
        _titleLab = [UILabel makeLabelWithText:@"" textColor:KWhiteColor font:mFont(19) textAliment:0];
    }
    return _titleLab;
}

- (UILabel *)detailLab{
    
    if (!_detailLab) {
        _detailLab = [UILabel makeLabelWithText:@"" textColor:KWhiteColor font:mFont(12) textAliment:0];
        _detailLab.adjustsFontSizeToFitWidth = YES;
    }
    return _detailLab;
}

- (OrderDetailFooterView *)footer{
    
    if (!_footer) {
        _footer = [[OrderDetailFooterView alloc] init];
        
        switch ([self.item.goStatus integerValue]) {
            case 1:
                _footer.orderStateType = OrderStateTyp_NoPaying;
                break;
            case 2:
                _footer.orderStateType = OrderStateType_NoSending;
                break;
            case 3:
                _footer.orderStateType = OrderStateType_NoAccept;
                break;
            case 4:
                _footer.orderStateType = OrderStateType_Finish;
                break;
            case 5:
                _footer.orderStateType = OrderStateType_Cancel;
                break;
                
                
            default:
                break;
        }
        
        
#pragma mark - 更多
        @weakify(self);
        _footer.dealMoreOperationBlock = ^{
            @strongify(self);
            [self showHudWithMsg:@"更多"];

        };
        
#pragma mark - 冷链物流
        _footer.dealLogisticsOrderBlock = ^{
            @strongify(self);
            
            LogisticsViewController *vc = [[LogisticsViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
#pragma mark - 去支付
        _footer.dealPayOrderBlock  = ^{
            @strongify(self);
            
            MeatPayViewController *vc = [[MeatPayViewController alloc] init];
            vc.parma = self.sumbitParam;
            [self.navigationController pushViewController:vc animated:YES];
        };
        
#pragma mark - 取消订单
        _footer.dealCancelOrderBlock  = ^{
            @strongify(self);
            
            OrderCancelBox *box = [[OrderCancelBox alloc] init];
            box.datas = self.reasons;
            box.selectBlock = ^(NSString * _Nonnull text) {
                
                [self requestCancelOrderById:self.item.goodsOrderId reason:text];
            };
            [box showView];
            
        };
        
#pragma mark - 朋友代付
        _footer.dealFriendPayOrderBlock  = ^{
            @strongify(self);
            
            [self showHudWithMsg:@"朋友代付"];
        };
        
#pragma mark - 继续逛逛
        _footer.dealBrowseOrderBlock  = ^{
            @strongify(self);
            
            [self showHudWithMsg:@"继续逛逛"];
        };
#pragma mark - 确认收货
        _footer.dealOkAcceptBlock  = ^{
            @strongify(self);
            
            [self showMyAlertWithTitle:@"" message:@"是否确认收到此订单商品？" confirmBtnTitle:@"确定" callBack:^{
                [self requestAcceptOrderById:self.item.goodsOrderId];
            }];
        };
#pragma mark - 晒单评价
        _footer.dealEvaluationOrderBlock  = ^{
            @strongify(self);
            
            [self showHudWithMsg:@"晒单评价"];
        };
        
#pragma mark - 追加评价
        _footer.dealAgainEvaluationOrderBlock  = ^{
            @strongify(self);
            
            [self showHudWithMsg:@"追加评价"];
        };
    }
    return _footer;
}

- (MeatOrderDetailResultModel *)model{
    
    if (!_model) {
        _model = [[MeatOrderDetailResultModel alloc] init];
    }
    return _model;
}

- (MeatOrderSumbitParam *)sumbitParam{
    
    if (!_sumbitParam) {
        _sumbitParam = [[MeatOrderSumbitParam alloc] init];
        _sumbitParam.memberId = kMemberId;
        _sumbitParam.shopId = @1;
        _sumbitParam.remark = @"";
        _sumbitParam.goType = @"4";
        _sumbitParam.memberStatus = @1;
    }
    return _sumbitParam;
}


- (NSArray *)reasons{
    
    if (!_reasons) {
        _reasons = @[@"我不想要了", @"信息填写有误，重新拍", @"下错单了，取消重新下单", @"等待时间太长", @"其它原因"];
    }
    return _reasons;
}


#pragma mark - override methods

- (void)registerTableViewCell{
    
    [self.tableView registerClass:[MeatOrderLocationCell class] forCellReuseIdentifier:@"MeatOrderLocationCell"];
    [self.tableView registerClass:[OrderDetailCommonCell class] forCellReuseIdentifier:@"OrderDetailCommonCell"];
    
    [self.tableView registerClass:[OrderNomalCell class] forCellReuseIdentifier:@"OrderNomalCell"];
    [self.tableView registerClass:[OrderHeaderCell class] forCellReuseIdentifier:@"OrderHeaderCell"];
    [self.tableView registerClass:[OrderDetailFooterCell class] forCellReuseIdentifier:@"OrderDetailFooterCell"];
    [self.tableView registerClass:[OrderBodyCell class] forCellReuseIdentifier:@"OrderBodyCell"];

    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_header.hidden = YES;
    self.tableView.backgroundColor = KClearColor;

    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 10)];
    view.backgroundColor = mBackgroudColor;
    self.tableView.tableFooterView = view;
}


@end
